---
import TocItem from './TocItem.astro';
const { headings } = Astro.props;
const toc = buildToc(headings);

function buildToc(headings) {
  const toc = [];
  const parentHeadings = new Map();
  headings.forEach((h) => {
    const heading = { ...h, subheadings: [] };
    parentHeadings.set(heading.depth, heading);
    if (heading.depth === 2) {
      toc.push(heading);
    } else {
      parentHeadings.get(heading.depth - 1).subheadings.push(heading);
    }
  });
  return toc;
}
---

<nav class="g-toc" id="Jtoc">
  <h5>TOC</h5>
  <ul class="toc-list">
    {toc.map((heading) => <TocItem heading={heading} />)}
  </ul>
</nav>